package com.vincent.kdp.Activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.vincent.baseapp.util.CommonUtil;
import com.vincent.baseapp.util.SPUtil;
import com.vincent.kdp.R;
import com.vincent.kdp.adapter.GetGoodsListAdapter;
import com.vincent.kdp.bean.GoodsListBean;
import com.vincent.kdp.bean.Paginator;
import com.vincent.kdp.http.RequestCallBack;
import com.vincent.kdp.repository.CheckGoodsRepository;
import com.vincent.kdp.ui.bean.entity.CommodityDetail;
import com.vincent.kdp.ui.bean.response.CommodityDetailOutput;
import com.vincent.kdp.ui.bean.response.ConfirmGoodsOutput;
import com.vincent.kdp.ui.bean.response.Msg;
import com.vincent.kdp.ui.bean.response.WaitConfirmListOutput;
import com.vincent.kdp.ui.commodity.repository.CommodityDetailRepository;
import com.vincent.kdp.ui.decoration.DividerItemDecoration;
import com.vincent.kdp.util.BaseParam;
import com.vincent.kdp.util.InventoryApi;
import com.vincent.kdp.util.RegexUtils;
import com.vincent.kdp.util.StringToHex;
import com.vincent.kdp.util.UhfDev;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 收货Activity
 */
public class ReceiveActivity extends Activity{
    @Bind(R.id.buttonStart)
    Button buttonStart;
    @Bind(R.id.buttonUpdate)
    Button buttonUpdate;
    @Bind(R.id.textViewTagReadNum)
    TextView textViewTagReadNum;
    @Bind(R.id.textViewTagUpdateNum)
    TextView textViewTagUpdateNum;
    @Bind(R.id.textViewBatch)
    TextView textViewBatch;
    /*@Bind(R.id.listViewData)
    ListView listView;*/

    @Bind(R.id.back_img)
    ImageView mBackImg;
    @Bind(R.id.toolbar_center_tv)
    TextView mToolbarCenterTv;

    @Bind(R.id.goodsRecyclerView)
    RecyclerView goodsRecyclerView;
    @Bind(R.id.mySwipeRefreshLayout)
    SwipeRefreshLayout mySwipeRefreshLayout;


    CommodityDetailRepository commodityDetailRepository=new CommodityDetailRepository();
    CheckGoodsRepository checkGoodsRepository=new CheckGoodsRepository();
    InventoryApi api;

    private ArrayList<Map<String, String>> listData = new ArrayList<Map<String, String>>();

    public Map<String,String> tagMap=new HashMap<String,String>();

    //private SimpleAdapter adapter;

    private ProgressDialog progressDialog;

    private int goodsNum;
    private  String batchCode;

    public  boolean hasNext=true;
    private int pageNum = 1;//请求页数，默认请求第一条
    boolean isLoading;
    private List<GoodsListBean.MyGoodsData.MyGoodsList> data = new ArrayList<>();
    private GetGoodsListAdapter adapter = new GetGoodsListAdapter(this, data);
    private ReceiveActivity thisActivity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive);
        ButterKnife.bind(this);
        getParam(getIntent());
        initView();
        connectUhf();
        initData();
    }

    private void initData() {
        String number= BaseParam.getDeviceId();
        commodityDetailRepository.reqCommodityList(batchCode, number, new RequestCallBack<GoodsListBean>() {
            @Override
            public void onSuccess(GoodsListBean bean) {
                GoodsListBean.MyGoodsData.MyPaginator paginator=bean.getData().getPaginator();
                if(bean.getData().getList().size()==0){

                }else if(thisActivity.hasNext){
                    data.addAll(bean.getData().getList());
                    mySwipeRefreshLayout.setRefreshing(false);
                    adapter.notifyItemRemoved(adapter.getItemCount());
                    thisActivity.pageNum=thisActivity.pageNum+1;
                    thisActivity.hasNext=paginator.isHasNextPage();
                    adapter.notifyDataSetChanged();
                }else{
                    Log.d("test", "没有更多数据" );
                    adapter.notifyItemRemoved(adapter.getItemCount());
                }
                mySwipeRefreshLayout.setRefreshing(false);
            }
            @Override
            public void onFalse(String msg) {
                mySwipeRefreshLayout.setRefreshing(false);
            }
        });
    }
    private void getParam(Intent intent){
        goodsNum=intent.getIntExtra("goodsNum",0);
        batchCode= RegexUtils.trimNull(intent.getStringExtra("batchCode"));
    }

    private void initView(){
        thisActivity=this;
        mToolbarCenterTv.setText("待收货品列表");
        textViewTagReadNum.setText(goodsNum+"张");
        textViewBatch.setText(batchCode);

        /*listView.setDivider(new ColorDrawable(Color.GRAY));
        listView.setDividerHeight(1);
        adapter =new SimpleAdapter(
                this, listData,
                R.layout.item_receive, new String[]{"code", "name",
                "val"}, new int[]{R.id.textView_code,
                R.id.textView_name, R.id.textView_val});
        listView.setAdapter(adapter);*/
        mySwipeRefreshLayout.setProgressViewOffset(false, 70, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 90, getResources()
                        .getDisplayMetrics()));
        mySwipeRefreshLayout.setColorSchemeResources(R.color.black);
        mySwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mySwipeRefreshLayout.setRefreshing(true);
            }
        });

        mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        goodsRecyclerView.setLayoutManager(layoutManager);

        goodsRecyclerView.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
        goodsRecyclerView.setAdapter(adapter);
        goodsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    if(thisActivity.hasNext){
                        Log.d("test", "loading executed");
                        boolean isRefreshing = mySwipeRefreshLayout.isRefreshing();
                        if (isRefreshing) {
                            adapter.notifyItemRemoved(adapter.getItemCount());
                            return;
                        }
                        if (!isLoading) {
                            isLoading = true;
                            initData();
                        }
                    }else{

                    }
                }
            }
        });
    }

    private void connectUhf(){
        api=InventoryApi.instance(this);
        String ip=SPUtil.getString("UHF_IP");
        api.setIp(ip);
        String ret=api.connectReader();
        if("0000".equals(ret)){

        }else{
            dialog(ret);
        }

        api.setHandleFuncAndCallback(msgHandler);

    }

    @OnClick({R.id.buttonStart,R.id.buttonUpdate})
    @SuppressLint("SimpleDateFormat")
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buttonStart:
                startInventory();
                break;
            case R.id.buttonUpdate:
                reqConfirmGoods();
                break;
            default:
                break;
        }
    }

    private void startInventory(){
        String ret=api.connectReader();
        if("开始收货".equals(buttonStart.getText())){
            buttonStart.setText("停止收货");
            api.startInventory();
        }else{
            buttonStart.setText("开始收货");
            api.stopInventory();
        }
    }

    private boolean isInBatch(String code){
       for(GoodsListBean.MyGoodsData.MyGoodsList item:data){
           if(code.equals(item.getBarCode())){
               item.setStatusText("已扫描");
               return true;
           }
       }
        return false;
    }


    private void addToListView(final String epcCount) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                synchronized (ReceiveActivity.this){
                    String[] tagArr = epcCount.split(";");
                    String epc = tagArr[0];

                    if(epc.length()<26){
                        Log.w("EPC",epc+"的编码格式不正确,要求大于26位");
                        return;
                    }

                    String hex=epc.substring(0,26);
                    final String barCode= StringToHex.convertHexToString(hex);
                    isInBatch(barCode);
                    adapter.notifyDataSetChanged();
                }

            }
        });
    }

    public void reqConfirmGoods(){
        progressDialog = ProgressDialog.show(ReceiveActivity.this, "正在加载", "请稍候", true, false);
        api.stopInventory();
        StringBuffer barList=new StringBuffer();
        for(int i=0;i<data.size();i++){
            GoodsListBean.MyGoodsData.MyGoodsList item=data.get(i);
            barList.append(item.getBarCode());
            if(i<data.size()-1){
                barList.append(",");
            }
        }
        checkGoodsRepository.reqcConfirmGoods(barList.toString(), new RequestCallBack<ConfirmGoodsOutput>() {
            @Override
            public void onSuccess(ConfirmGoodsOutput output) {
                List<Msg> list=output.getData();
                Map msgMap=new HashMap();
                for(Msg msg:list){
                    msgMap.put(msg.getBarCode(),msg);
                }
                int successNum=0;
                for(GoodsListBean.MyGoodsData.MyGoodsList item:data){
                    Msg msg=(Msg)msgMap.get(item.getBarCode());
                    if(msg.result){
                        item.setStatusText("已入库");
                        successNum=successNum+1;
                    }else{
                        item.setStatusText(msg.getRetMsg());
                    }
                }
                textViewTagUpdateNum.setText(successNum+"张");
                adapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }

            @Override
            public void onFalse(String msg) {
                progressDialog.dismiss();
            }
        });
    }

    public void sumPriceAndWeight(){
        double act=0;
        double weight=0;
        for(int i=0;i<listData.size();i++){
            Map map=(Map)listData.get(i);
            Object valObj=map.get("val");
            if("1".equals(map.get("chargeUnit").toString())){
                double wt=0;
                if(valObj!=null){
                    try {
                        wt=Double.parseDouble(valObj.toString());
                    }catch (Exception e){

                    }
                }
                weight=weight+wt;
            }else{
                double price=0;
                if(valObj!=null){
                    try {
                        price=Double.parseDouble(valObj.toString());
                    }catch (Exception e){

                    }
                }
                act=act+price;
            }
        }
    }

    public Handler msgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String str = msg.getData().getString("msg");
            if ((null == str || 0 == str.length())
                    && ((UhfDev.MSG_TIMER != msg.what)
                    && (msg.what != UhfDev.MSG_PAUSE)
                    && (msg.what != UhfDev.MSG_RESUME)))
                return;
            if (msg.what == UhfDev.MSG_EPC) { // 标签内容
                String epc = str;
                addToListView(epc);
            } else if (msg.what == UhfDev.MSG_OPEN) { // 连接

            } else if (msg.what == UhfDev.MSG_TIMER) { // 定时器

            } else if (msg.what == UhfDev.MSG_PAUSE) { // 暂停
                startInventory();
            } else if (msg.what == UhfDev.MSG_RESUME) { // 继续
                startInventory();
            } else { // 消息
            }
        }
    };


    @OnClick(R.id.back_img)
    public void onClick() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("是否退出收货?");
        builder.setTitle("提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                api.stopInventory();
                finish();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }

    public void dialog(String msg){
        AlertDialog.Builder builder = new AlertDialog.Builder(ReceiveActivity.this);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


}
